package com.ruoyi.system.apiService.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.apiResult.ApiRe;
import com.ruoyi.common.apiResult.Result;
import com.ruoyi.common.apiResult.ZhtcRe;
import com.ruoyi.common.cache.CacheComponent;
import com.ruoyi.common.utils.BeanUtil;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.common.utils.GeneratorUtil;
import com.ruoyi.common.utils.SpringContextUtil;
import com.ruoyi.system.aikeService.ToZhtcApiService;
import com.ruoyi.system.apiQuery.*;
import com.ruoyi.system.apiService.HomeParkService;
import com.ruoyi.system.apiService.OrderService;
import com.ruoyi.system.apiService.ZhtcService;
import com.ruoyi.system.common.WebsocketMsg;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.dto.GetParkFeeDTO;
import com.ruoyi.system.dto.OrderProductListDTO;
import com.ruoyi.system.dto.ScanChannelCodeInOutDTO;
import com.ruoyi.system.dto.SendplateticketQuery;
import com.ruoyi.system.host.ServerPark;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.ruoyi.system.mqtt.*;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class HomeParkServiceImpl implements HomeParkService {

	@Autowired
	private CommonMapper commonMapper;
	@Autowired
	private ZsyyParkMapper parkMapper;

	@Autowired
	private ZsyyParkEnterMapper parkEnterMapper;

	@Autowired
	private ZsyyParkLeaveMapper parkLeaveMapper;

	@Autowired
	private ZsyyParkCarMapper parkCarMapper;
	@Autowired
	private ZsyyParkEnterPayMapper parkEnterPayMapper;
	@Autowired
	private ZsyyChannelInfoMapper channelInfoMapper;
	@Autowired
	private ToZhtcApiService toZhtcApiService;
	@Autowired
	private ZsyyParkTicketMapper parkTicketMapper;
	@Autowired
	private ZsyyParkTicketTypeMapper parkTicketTypeMapper;
	@Autowired
	private ServerPark hostPark;

	@Autowired
	private OrderService orderService;

	@Autowired
	private CacheComponent cacheComponent;  //Redis

	@Autowired
	private MqttService mqttService;

	private SpringContextUtil springContextUtil =new SpringContextUtil();

	@Value("${etc.apiurl}")
	private String etcUrl;
	@Value("${etc.merchantNo}")
	private String merchantNo;


	@Override
	public synchronized ZhtcRe getParkFee(GetParkFeeQuery param) throws Exception{
		ZhtcRe re = new ZhtcRe();
//        String sql = "SELECT t1.*,t2.park_name FROM `zsyy_park_enter` t1 join zsyy_park t2 on t1.park_code = t2.park_code where t1.park_code = #{parkCode} and t1.status =1 ";
//        Map params = new HashMap();
//        params.put("parkCode",param.getParkCode());
//        if(!StringUtils.isEmpty(param.getUserUniqCode())){
//            sql +=" and t1.user_uniq_code =#{userUniqCode} ";
//            params.put("userUniqCode",param.getUserUniqCode());
//        }
//        if(!StringUtils.isEmpty(param.getParkingCode())){
//            sql +=" and t1.parking_code =#{parkingCode} ";
//            params.put("parkingCode",param.getParkingCode());
//        }
//        if(!StringUtils.isEmpty(param.getCarCode())){
//            sql +=" and t1.car_license_number =#{carCode} ";
//            params.put("carCode",param.getCarCode());
//        }
//        sql += " order by t1.createtime desc limit 1";
//
//        params.put("sql",sql);
//        ParkEnter parkEnter = parkEnterMapper.getEnty(params);
//        if(parkEnter==null){
//            re =new ZhtcRe(0);
//            re.setMessage("没有查到相关停车记录");
//            return re;
//        }
//        sql = "SELECT * FROM `zsyy_park_leave` where leave_status=0  and car_license_number =#{carNo} and createtime >#{createtime} ORDER BY id desc limit 1 ";
//        params.put("sql",sql);
//        params.put("carNo",parkEnter.getCarLicenseNumber());
//        params.put("createtime",new Date(new Date().getTime()-1000*60*5));
//        ParkLeave parkLeave = parkLeaveMapper.getEnty(params);

		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
//        dataItem.put("recordNo",parkEnter.getParkingCode());
		dataItem.put("plateNumber",param.getCarCode());


		dataItem.put("payScene",0);
		if(param.getCarCode().indexOf("无")!=-1&&!StringUtils.isEmpty(param.getOutChannelid())){
			//无牌车
			dataItem.put("outChannelid",param.getOutChannelid());
			dataItem.put("payScene",2);
		}else if(!StringUtils.isEmpty(param.getOutChannelid())){
//            通道扫码
			dataItem.put("payScene",1);
			dataItem.put("outChannelid",param.getOutChannelid());
		}


		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCode());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setServiceId("pay.queryfeebyplate");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			Map mqData = (Map)mqttQuery.getDataItems().get(0);
			GetParkFeeDTO reData = new GetParkFeeDTO();
//            BeanUtil.copyPropertiesIgnoreNull(parkEnter,reData);
			reData.setCarCode(param.getCarCode());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date enterTime = sdf1.parse(mqData.get("enterTime").toString());

			String enterDate = sdf.format(enterTime);
			reData.setEnterDate(enterDate);
			reData.setChargeDate(enterDate);
			reData.setParkingCode(mqData.get("recordNo").toString());
			reData.setParkingFee(Double.parseDouble(mqData.get("payableFee").toString()));//总金额
			reData.setParkingTime((int)mqData.get("useTime")/60l);
			reData.setPaidValue(0);
			reData.setShouldPayValue(Double.parseDouble(mqData.get("paidFee").toString()));//应付金额
			reData.setDiscountedValue(Double.parseDouble(mqData.get("discountFee").toString()));//优惠金额

			re.setData(reData);

		}else {
			re =new ZhtcRe(0);
			re.setMessage(mqttQuery.getMsg());
			return re;
		}

		return re;
	}

	@Override
	public synchronized ApiRe getParkFeeMqtt(GetParkFeeQuery param, long userId) throws Exception{
		ApiRe re = new ApiRe();
//        String sql = "SELECT t1.*,t2.park_name FROM `zsyy_park_enter` t1 join zsyy_park t2 on t1.park_code = t2.park_code where t1.park_code = #{parkCode} and t1.status =1 ";
//        Map params = new HashMap();
//        params.put("parkCode",param.getParkCode());
//        if(!StringUtils.isEmpty(param.getUserUniqCode())){
//            sql +=" and t1.user_uniq_code =#{userUniqCode} ";
//            params.put("userUniqCode",param.getUserUniqCode());
//        }
//        if(!StringUtils.isEmpty(param.getParkingCode())){
//            sql +=" and t1.parking_code =#{parkingCode} ";
//            params.put("parkingCode",param.getParkingCode());
//        }
//        if(!StringUtils.isEmpty(param.getCarCode())){
//            sql +=" and t1.car_license_number =#{carCode} ";
//            params.put("carCode",param.getCarCode());
//        }
//        sql += " order by t1.createtime desc limit 1";
//
//        params.put("sql",sql);
//        ParkEnter parkEnter = parkEnterMapper.getEnty(params);
//        if(parkEnter==null){
//            re =new ApiRe(0);
//            re.setMsg("没有查到相关停车记录");
//            return re;
//        }
//
//        sql = "SELECT * FROM `zsyy_park_leave` where leave_status=0  and car_license_number =#{carNo} and createtime >#{createtime} ORDER BY id desc limit 1 ";
//        params.put("sql",sql);
//        params.put("carNo",parkEnter.getCarLicenseNumber());
//        params.put("createtime",new Date(new Date().getTime()-1000*60*5));
//        ParkLeave parkLeave = parkLeaveMapper.getEnty(params);
//        List dataItems = new ArrayList();
//        Map dataItem = new HashMap();
//        dataItem.put("recordNo",parkEnter.getLockKey());
//        dataItem.put("plateNumber",parkEnter.getCarLicenseNumber());
//
//        dataItem.put("payScene",0);
//        if(parkEnter.getCarLicenseNumber().indexOf("无")!=-1&&!StringUtils.isEmpty(param.getOutChannelid())){
//            //无牌车
//            dataItem.put("outChannelid",param.getOutChannelid());
//            dataItem.put("payScene",2);
//        }else if(!StringUtils.isEmpty(param.getOutChannelid())&&parkLeave!=null){
////            通道扫码
//            dataItem.put("payScene",1);
//            dataItem.put("outChannelid",param.getOutChannelid());
//        }
//        dataItems.add(dataItem);
//        MqttQuery mqttQuery = new MqttQuery();
//        mqttQuery.setParkCode(parkEnter.getParkCode());
//        mqttQuery.setDataItems(dataItems);
//        mqttQuery.setCode(1);
//        mqttQuery.setServiceId("pay.queryfeebyplate");
//        mqttQuery = mqttService.commonMqtt(mqttQuery);

		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
//        dataItem.put("recordNo",parkEnter.getParkingCode());
		dataItem.put("plateNumber",param.getCarCode());


		dataItem.put("payScene",0);
		if(param.getCarCode().indexOf("无")!=-1&&!StringUtils.isEmpty(param.getOutChannelid())){
			//无牌车
			dataItem.put("outChannelid",param.getOutChannelid());
			dataItem.put("payScene",2);
		}else if(!StringUtils.isEmpty(param.getOutChannelid())){
//            通道扫码
			dataItem.put("payScene",1);
			dataItem.put("outChannelid",param.getOutChannelid());
		}


		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCode());
		mqttQuery.setDataItems(dataItems);

		WebsocketMsg msg = new WebsocketMsg();
		if("2KST6MLE".equals(mqttQuery.getParkCode())){
			mqttQuery.setCode(1);
			mqttQuery.setServiceId("pay.queryfeebyplate");
			mqttQuery = mqttService.commonMqtt(mqttQuery);
			msg.setCode(2);
		}else {
			mqttQuery.setCode(2);

			Map data = new HashMap();
			data.put("carNo",param.getCarCode());
			data.put("parkingCode",param.getParkingCode());
			msg.setHostCode(param.getParkCode());
			msg.setData(data);
			msg = hostPark.getParkFee(msg);
		}
		if(mqttQuery.getCode()==1||msg.getCode()==0){
			Map mqData = null;
			GetParkFeeDTO reData = new GetParkFeeDTO();
			int price = 0;
			OrderProductListDTO order = new OrderProductListDTO();
			if(mqttQuery.getCode()==1){
				mqData = (Map)mqttQuery.getDataItems().get(0);
				mqData.put("parkCode",mqttQuery.getParkCode());
				price = (int)(Double.parseDouble(mqData.get("paidFee").toString())*100);
				order.setOrderTag(mqData.get("recordNo").toString());
			}else {
				mqData = (Map)msg.getData();
				mqData.put("parkCode",msg.getHostCode());
				reData = JSON.parseObject(JSON.toJSONString(mqData),GetParkFeeDTO.class);
				price = (int)(reData.getShouldPayValue()*100);
				order.setOrderTag(reData.getParkingCode());
			}

			mqData.put("outChannelid",param.getOutChannelid());

			if(price<=0){
				re.setCode(400);
				re.setMsg("您目前需缴费金额为零");
				return re ;
			}
			order.setType(3);
			order.setRemark(JSON.toJSONString(mqData));
			order.setPrice(price);
			order.setProductName("停车缴费");
			order.setActualPrice(price);

			//添加订单
			re = orderService.submitOrder(order,userId);
			if(re.getCode()==200){
				Map orderMap = (Map)re.getData();
				reData.setOrderId(Long.parseLong(orderMap.get("orderId").toString()));
				reData.setOrderNo(orderMap.get("orderNo").toString());
				reData.setActualPrice(Integer.parseInt(orderMap.get("actualPrice").toString()));


				if(mqttQuery.getCode()==1){
//                BeanUtil.copyPropertiesIgnoreNull(parkEnter,reData);
					reData.setCarCode(param.getCarCode());

					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
					SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date enterTime = sdf1.parse(mqData.get("enterTime").toString());

					String enterDate = sdf.format(enterTime);
					reData.setEnterDate(enterDate);
					reData.setChargeDate(enterDate);
					reData.setParkingFee(Double.parseDouble(mqData.get("payableFee").toString()));//总金额
					reData.setParkingTime((int)mqData.get("useTime")/60l);
					reData.setPaidValue(0);
					reData.setShouldPayValue(Double.parseDouble(mqData.get("paidFee").toString()));//应付金额
					reData.setDiscountedValue(Double.parseDouble(mqData.get("discountFee").toString()));//优惠金额

				}
				re.setData(reData);
			}


//            ParkLeave ple = new ParkLeave();
//            ple.setUserId(userId);
//            ple.setParkingCode(parkEnter.getParkingCode());
//            ple.setParkCode(parkEnter.getParkCode());
//            zhtcService.addParkLeave(ple);

		}else {
			re.setCode(400);
			re.setMsg(mqttQuery.getMsg());
			return re;
		}

		return re;
	}

	@Override
	public synchronized ZhtcRe payParkFeeMqtt(PayParkFeeQuery param) {
		ZhtcRe re = new ZhtcRe();
		Map mqtt = param.getMqtt();
		//生成订单号
		String orderNo = param.getBillCode();

		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
		dataItem.put("plateNumber",mqtt.get("plateNumber"));
		dataItem.put("orderNo",orderNo);
		dataItem.put("discountFee",param.getDiscountFee()!=null&&param.getDiscountFee()>0?param.getDiscountFee():0.1);
//        dataItem.put("discountFee",10);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dataItem.put("paidFee",param.getActPayCharge());
		dataItem.put("payTime",sdf.format(new Date() ));
		dataItem.put("payType",6);
		dataItem.put("payAuth", UUID.randomUUID().toString());
		dataItem.put("payAuthName","码上到位");
		dataItem.put("payPath",1000);
		dataItem.put("payPathDes","微信");
		dataItem.put("enterTime",mqtt.get("enterTime"));
		if(!StringUtils.isEmpty(mqtt.get("outChannelid"))){
			dataItem.put("payChannel",33);
			dataItem.put("outChannelid",mqtt.get("outChannelid"));
		}else {
			dataItem.put("payChannel",1);
		}

		dataItem.put("recordNo",mqtt.get("recordNo"));
		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(mqtt.get("parkCode").toString());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setServiceId("pay.payparkingfeeorder");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			ZsyyParkEnterPay parkEnterPay = new ZsyyParkEnterPay();
			BeanUtil.copyPropertiesIgnoreNull(param,parkEnterPay);
			parkEnterPay.setOrderNo(orderNo);
			parkEnterPayMapper.insert(parkEnterPay);

			//调取开闸
//            if(!StringUtils.isEmpty(param.getOutChannelid())){
//                OpGateQuery opGateQuery = new OpGateQuery();
//                opGateQuery.setParkCode(mqtt.get("parkCode").toString());
//                opGateQuery.setChannelCode(mqtt.get("outChannelid").toString());
//                opGateQuery.setOpType(0);
//                this.opGate(opGateQuery);
//            }


			Map map = new HashMap();
			map.put("parkCode",param.getParkCode());
			map.put("timeoutLength",60*10);
			map.put("ydtBillCode",orderNo);
			re.setData(map);

		}else {
			re =new ZhtcRe(0);
			re.setMessage(mqttQuery.getMsg());
			return re;
		}

		return re;
	}
	@Override
	public synchronized ZhtcRe payParkFee(PayParkFeeQuery param) {
		ZhtcRe re = new ZhtcRe();
//        ParkEnter parkEnter = new ParkEnter();
//        parkEnter.setParkingCode(param.getParkingCode());
//        parkEnter = parkEnterMapper.selectOne(parkEnter);
//        String sql = "SELECT t1.* FROM `zsyy_park_enter` t1  where t1.parking_code = #{parkingCode} limit 1 ";
		Map params = new HashMap();
//        params.put("parkingCode",param.getParkingCode());
//        params.put("sql",sql);
//        ParkEnter parkEnter = parkEnterMapper.getEnty(params);
//        if(parkEnter == null){
//            re.setResultCode(1);
//            re.setMessage("没有该停车记录");
//            return re;
//        }
		//生成订单号
		String orderNo = GeneratorUtil.genOrderId("40","msdw");

		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
		dataItem.put("plateNumber",param.getCarCode());
		dataItem.put("orderNo",orderNo);
		dataItem.put("discountFee",param.getDiscountFee()!=null&&param.getDiscountFee()>0?param.getDiscountFee():0.1);
//        dataItem.put("discountFee",10);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dataItem.put("paidFee",param.getActPayCharge());
		dataItem.put("payTime",sdf.format(new Date() ));
		dataItem.put("payType",6);
		dataItem.put("payAuth",UUID.randomUUID().toString());
		dataItem.put("payAuthName","码上到位");
		dataItem.put("payPath",1000);
		dataItem.put("payPathDes","微信");
		dataItem.put("enterTime",sdf.format(param.getChargeDate()));

//        String sql = "SELECT * FROM `zsyy_park_leave` where leave_status=0  and car_license_number =#{carNo} and createtime >#{createtime} ORDER BY id desc limit 1 ";
//        params.put("sql",sql);
//        params.put("carNo",param.getCarCode());
//        params.put("createtime",new Date(new Date().getTime()-1000*60*2));
//        ParkLeave parkLeave = parkLeaveMapper.getEnty(params);
		dataItem.put("payChannel",1);
		if(!StringUtils.isEmpty(param.getOutChannelid())){
			dataItem.put("payChannel",33);
			dataItem.put("outChannelid",param.getOutChannelid());
		}
//        else if(parkLeave!=null){
//            dataItem.put("payChannel",33);
//            dataItem.put("outChannelid",parkLeave.getLeaveChannelCode());
//        }

		dataItem.put("recordNo",param.getParkingCode());
		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCode());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setServiceId("pay.payparkingfeeorder");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			ZsyyParkEnterPay parkEnterPay = new ZsyyParkEnterPay();
			BeanUtil.copyPropertiesIgnoreNull(param,parkEnterPay);
			parkEnterPay.setOrderNo(orderNo);
			parkEnterPayMapper.insert(parkEnterPay);
//            BigDecimal b1 = new BigDecimal(parkEnter.getPayMoney());
//            BigDecimal b2 = new BigDecimal(param.getActPayCharge());
//            b1 = b1.add(b2);
//            parkEnter.setPayMoney(b1.doubleValue());
//            parkEnter.setPayTime(new Date());
//            parkEnterMapper.updateById(parkEnter);
			//调取开闸
//            if(!StringUtils.isEmpty(param.getOutChannelid())){
//                OpGateQuery opGateQuery = new OpGateQuery();
//                opGateQuery.setParkCode(parkEnter.getParkCode());
//                opGateQuery.setChannelCode(param.getOutChannelid());
//                opGateQuery.setOpType(0);
//                this.opGate(opGateQuery);
//            }


			Map map = new HashMap();
			map.put("parkCode",param.getParkCode());
			map.put("timeoutLength",60*10);
			map.put("ydtBillCode",orderNo);
			re.setData(map);

		}else {
			re =new ZhtcRe(0);
			re.setMessage(mqttQuery.getMsg());
			return re;
		}

		return re;
	}
	@Override
	public  ZhtcRe scanChannelCodeInOut(ScanChannelCodeInOutQuery param) {
		ZhtcRe re = new ZhtcRe();
		LambdaQueryWrapper<ZsyyChannelInfo> lqw = Wrappers.lambdaQuery();
		lqw.eq(ZsyyChannelInfo::getParkCode,param.getParkCode());
		lqw.eq(ZsyyChannelInfo::getChannelCode,param.getChannelSeq());
		ZsyyChannelInfo channelInfo = channelInfoMapper.selectOne(lqw);
		if(channelInfo==null){
			re.setStatus(2);
			re.setResultCode(1);
			re.setMessage("该通道不存在");
			return re;
		}


		Map params = new HashMap();
		params.put("parkCode",param.getParkCode());
		params.put("channelSeq",param.getChannelSeq());
		String sql = null;
		ScanChannelCodeInOutDTO reDto = new ScanChannelCodeInOutDTO();
		String parkCode = param.getParkCode();
		reDto.setParkCode(param.getParkCode());
		reDto.setChannelSeq(param.getChannelSeq()+"");
		if(channelInfo.getEntranceType()==1){
			//入口
			if("2KST6MLE".equals(parkCode)){
				sql = "SELECT * FROM `zsyy_park_enter` where  park_code =#{parkCode} and channel_id =#{channelSeq} ORDER BY id desc limit 1 ";
			}else {
				sql = "SELECT * FROM `zsyy_park_enter` where  park_code =#{parkCode} and enter_channel_code =#{channelSeq} ORDER BY id desc limit 1 ";
			}

			params.put("sql",sql);
			ZsyyParkEnter parkEnter = parkEnterMapper.getEnty(params);
			parkEnter.setUserUniqCode(param.getUserUniqCode());
			reDto.setSelfInRandomCode(parkEnter.getSelfInRandomCode());
			reDto.setCarCode(parkEnter.getCarLicenseNumber());
			reDto.setPassType(1);
			reDto.setIsParkInOut(1);
			reDto.setCode(1);
			reDto.setIsPaid(0);
			reDto.setParkingCode(parkEnter.getParkingCode());
			parkEnterMapper.updateById(parkEnter);

		}else if(channelInfo.getEntranceType()==2){
			//出口
			if("2KST6MLE".equals(parkCode)){
				sql = "SELECT * FROM `zsyy_park_leave` where leave_status=0 and park_code =#{parkCode} and channel_id =#{channelSeq} and createtime >#{createtime} ORDER BY id desc limit 1 ";
			}else {
				sql = "SELECT * FROM `zsyy_park_leave` where leave_status=0 and park_code =#{parkCode} and leave_channel_code =#{channelSeq} and createtime >#{createtime} ORDER BY id desc limit 1 ";
			}
			params.put("sql",sql);
			params.put("createtime",new Date(new Date().getTime()-1000*60*5));
			ZsyyParkLeave parkLeave = parkLeaveMapper.getEnty(params);
			if(parkLeave==null){
				re.setMessage("该通道没有车辆");
				return re;
			}
			params.put("enterTime",parkLeave.getEnterTime());
			params.put("carNo",parkLeave.getCarLicenseNumber());
			if("2KST6MLE".equals(parkCode)){
				sql = "SELECT * from zsyy_park_enter where status=1 and park_code = #{parkCode} and car_license_number =#{carNo} order by id desc limit 1";
			}else {
				sql = "SELECT * from zsyy_park_enter where enter_time = #{enterTime} and park_code = #{parkCode} and car_license_number =#{carNo} ";
			}

			params.put("sql",sql);
			reDto.setCarCode(parkLeave.getCarLicenseNumber());
			reDto.setPassType(2);
			reDto.setIsParkInOut(1);
			reDto.setCode(1);
			reDto.setIsPaid(0);
			reDto.setPlateId(parkLeave.getLockKey());
			ZsyyParkEnter parkEnter = parkEnterMapper.getEnty(params);
			if(parkEnter!=null){
				reDto.setSelfInRandomCode(parkEnter.getSelfInRandomCode());
				BigDecimal b1 =  parkLeave.getTotalAmount();
				BigDecimal b2 = new BigDecimal(String.valueOf(parkEnter.getPayMoney()));
				b1 = b1.subtract(b2);
				reDto.setAmount(b1.doubleValue()>0?b1.doubleValue():0);
				reDto.setParkingCode(parkEnter.getParkingCode());
			}


		}
		re.setData(reDto);

		return re;
	}

	@Override
	public  ZhtcRe opGate(OpGateQuery param) {
		ZhtcRe re = new ZhtcRe();
		String action = null;
		if(param.getOpType()==0){
			//开
			action = "opengate";
		}else if(param.getOpType()==1){
			//关
			action = "closegate";
		}else{
			re.setStatus(2);
			re.setResultCode(1);
			re.setMessage("opType参数错误");
			return re;
		}
		Result result = mqttService.openOrclosegate(action,Integer.parseInt(param.getChannelCode()),param.getParkCode());
		if(result.getCode().getCode() != 0){
			re.setStatus(2);
			re.setResultCode(1);
			re.setMessage(result.getMessage());
		}

		return re;
	}

	@Override
	public ZhtcRe addOnlineMonthTicketType(AddOnlineMonthTicketTypeQuery param) {
		ZhtcRe re = new ZhtcRe();
		ZsyyParkTicketType parkTicketType = new ZsyyParkTicketType();
		BeanUtil.copyPropertiesIgnoreNull(param,parkTicketType);
		parkTicketType.setStartTime(param.getTimePeriod().getStartTime());
		parkTicketType.setEndTime(param.getTimePeriod().getEndTime());
		List dataItems = new ArrayList();
		MqttCarGroupVo m = new MqttCarGroupVo();
		m.setBeginTime(DateUtil.format(param.getTimePeriod().getStartTime(),"yyyy-MM-dd HH:mm:ss"));
		m.setEndTime(DateUtil.format(param.getTimePeriod().getEndTime(),"yyyy-MM-dd HH:mm:ss"));
		m.setGroupName(param.getTicketName());
		m.setGroupNum(9999);
		m.setID(0);
		m.setIsFree(1);
		m.setGroupTel("13123456789");
		m.setCreateTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
		m.setRemark(param.getRemark());
		m.setUnitFee(Double.parseDouble(param.getPrice()));
		m.setLeftNum(9999);
		m.setParkCode(param.getParkCodes());
		dataItems.add(m);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCodes());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setAction("add");
		mqttQuery.setServiceId("manage.cargroups");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			Map mqData = (Map)mqttQuery.getDataItems().get(0);
			Map map = new HashMap();
			map.put("monthTicketConfigId",mqData.get("ID"));
			re.setData(map);
		}else {
			re.setStatus(2);
			re.setResultCode(1);
			re.setMessage(mqttQuery.getMsg());
		}
		return re;
	}

	@Override
	public ZhtcRe addOnlineMonthTicket(AddOnlineMonthTicketQuery param) {
		ZhtcRe re = new ZhtcRe();
//        ParkTicket parkTicket = new ParkTicket();
//        BeanUtil.copyPropertiesIgnoreNull(param,parkTicket);
//        parkTicket.setStartTime(param.getTimePeriodList().get(0).getStartTime());
//        parkTicket.setEndTime(param.getTimePeriodList().get(0).getEndTime());

		List dataItems = new ArrayList();
		MqttCarVo mqttCar = new MqttCarVo();
		mqttCar.setCarNum(param.getCarNo());//车牌号
		mqttCar.setOwner(param.getUserName());//车主名称
		mqttCar.setCarTypeCode(11);//车辆类型编码
		mqttCar.setRemark(param.getPayOriginRemark());//备注
		mqttCar.setState(1);//启用状态
		mqttCar.setCarSpaceNum("1");//车位号
		mqttCar.setTel(param.getUserPhone());//车主电话
		mqttCar.setTimeEnd(DateUtil.format(param.getTimePeriodList().get(0).getEndTime(),"yyyy-MM-dd HH:mm:ss")); //有效结束时间
		mqttCar.setTimeStart(DateUtil.format(param.getTimePeriodList().get(0).getStartTime(),"yyyy-MM-dd HH:mm:ss")); //有效开始时间
		mqttCar.setCarMMoney(param.getFavorPrice());//月费标准
		mqttCar.setBalance(0d);//余额
		mqttCar.setCarGroup("");//车组名称
//        mqttCar.setCarGroupID(param.getMonthTicketConfigId().intValue()); //车组ID
		mqttCar.setParkCode(param.getParkCodes());
		if(param.getID()!=null&&param.getID()>0){
			mqttCar.setID((int)((long)param.getID()));
		}
		dataItems.add(mqttCar);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCodes());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setAction(param.getAction());
		mqttQuery.setServiceId("manage.cars");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			Map map = new HashMap();
			if(mqttQuery.getDataItems()!=null&&mqttQuery.getDataItems().size()>0){
				Map mqData = (Map)mqttQuery.getDataItems().get(0);
				map.put("monthTicketId",mqData.get("ID"));
				re.setData(map);
			}else {
				map.put("monthTicketId",param.getID());
				re.setData(map);
			}

		}else {
			re.setStatus(2);
			re.setResultCode(1);
			re.setMessage(mqttQuery.getMsg());
		}

		return re;
	}

	@Override
	public ZhtcRe cancelOnlineVipTicket(long monthTicketId,String parkCode) {
		ZhtcRe re = new ZhtcRe();
//        ParkTicket parkTicket = new ParkTicket();
//        BeanUtil.copyPropertiesIgnoreNull(param,parkTicket);
//        parkTicket.setStartTime(param.getTimePeriodList().get(0).getStartTime());
//        parkTicket.setEndTime(param.getTimePeriodList().get(0).getEndTime());

		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
		dataItem.put("ID",monthTicketId);
		dataItem.put("UUID","msdw"+DateUtil.format(new Date(),"yyyyMMddHHmmss"));

		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(parkCode);
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setAction("delete");
		mqttQuery.setServiceId("manage.cars");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
//        if(mqttQuery.getCode()==1){
//
//        }else {
//            re.setStatus(2);
//            re.setResultCode(1);
//            re.setMessage(mqttQuery.getMsg());
//        }

		return re;
	}

	@Override
	public ZhtcRe sendplateticket(SendplateticketQuery param) {
		ZhtcRe re = new ZhtcRe();
		List dataItems = new ArrayList();
		param.setTicketMark("msdw"+new Date().getTime());
		param.setTicketNo("msdw"+new Date().getTime());
		if(param.getFreeTicketType()!=null&&param.getFreeTicketType()==1){
			param.setTicketType("5");
		}else {
			param.setFreeTicketType(0);
			param.setTicketType("1");
		}

		dataItems.add(param);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCode());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setServiceId("pay.sendplateticket");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			if(mqttQuery.getDataItems().size()>0){
				Map mqData = (Map)mqttQuery.getDataItems().get(0);
				re.setData(mqData);
			}


		}else {
			re =new ZhtcRe(0);
			re.setMessage(mqttQuery.getMsg());
			return re;
		}

		return re;
	}

	@Override
	public ZhtcRe addBlackListCar( AddBlackListCarQuey param) {
		ZhtcRe re = new ZhtcRe();
		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
		dataItem.put("id",0);
		dataItem.put("carNum",param.getCarNum());
//        dataItem.put("operator",operator);
		dataItem.put("duration",param.getDuration());
		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCode());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setAction("add");
		mqttQuery.setServiceId("manage.blacklist");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getDataItems()!=null&&mqttQuery.getCode()==1){
			if(mqttQuery.getDataItems().size()>0){
				Map mqData = (Map)mqttQuery.getDataItems().get(0);
				re.setData(mqData);
			}


		}else {
			re =new ZhtcRe(0);
			re.setMessage(mqttQuery.getMsg());
			return re;
		}

		return re;
	}

	@Override
	public ZhtcRe removeBlackListCar(Long id,String parkCode) {
		ZhtcRe re = new ZhtcRe();
		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
		dataItem.put("id",id);
		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(parkCode);
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setAction("delete");
		mqttQuery.setServiceId("manage.blacklist");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			if(mqttQuery.getDataItems()!=null&&mqttQuery.getDataItems().size()>0){
				Map mqData = (Map)mqttQuery.getDataItems().get(0);
				re.setData(mqData);
			}


		}else {
			re =new ZhtcRe(0);
			re.setMessage(mqttQuery.getMsg());
			return re;
		}

		return re;
	}

	@Override
	public ZhtcRe recordInNocarnum(RecordInNocarnumQuery param) {
		ZhtcRe re = new ZhtcRe();
		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		dataItem.put("plateNumber",param.getPlateNumber());
		dataItem.put("channelid",param.getChannelid());
		dataItem.put("requestTime",sdf.format(new Date()));
		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCode());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setServiceId("record.in.nocarnum");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			if(mqttQuery.getDataItems()!=null&&mqttQuery.getDataItems().size()>0){
				Map mqData = (Map)mqttQuery.getDataItems().get(0);
				re.setData(mqData);
			}


		}else {
			re =new ZhtcRe(0);
			re.setMessage(mqttQuery.getMsg());
			return re;
		}

		return re;
	}
	@Override
	public ZhtcRe manageParkout(ManageParkoutQuery param) {
		ZhtcRe re = new ZhtcRe();
		List dataItems = new ArrayList();
		Map dataItem = new HashMap();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		dataItem.put("plateNumber",param.getPlateNumber());
		dataItem.put("outChannelId",param.getOutChannelId());
		dataItem.put("requestTime",sdf.format(new Date()));
		dataItems.add(dataItem);
		MqttQuery mqttQuery = new MqttQuery();
		mqttQuery.setParkCode(param.getParkCode());
		mqttQuery.setDataItems(dataItems);
		mqttQuery.setCode(1);
		mqttQuery.setAction("preoutedit");
		mqttQuery.setServiceId("manage.parkout");
		mqttQuery = mqttService.commonMqtt(mqttQuery);
		if(mqttQuery.getCode()==1){
			if(mqttQuery.getDataItems()!=null&&mqttQuery.getDataItems().size()>0){
				Map mqData = (Map)mqttQuery.getDataItems().get(0);
				re.setData(mqData);
			}


		}else {
			re =new ZhtcRe(0);
			re.setMessage(mqttQuery.getMsg());
			return re;
		}

		return re;
	}

	@Override
	public void myReceivedMsg(String param) {
		try{
			Map mapParam = JSON.parseObject(param,Map.class);
			Class<?> clazz = Class.forName("com.appapi.service.mypark.MyParkService");
			Method method = clazz.getMethod( mapParam.get("cmd").toString(),Map.class);
			Object obj1 = method.invoke(springContextUtil.getBean(clazz),mapParam);
		}catch (Exception e){
			e.printStackTrace();
		}

	}

	@Override
	public void myRetrunMsg(String param) {
		int index = param.indexOf("uuid")+7;
		String uuid = param.substring(index,index+36);
		cacheComponent.putRaw(uuid,param,60);
	}

	@Override
	public ZhtcRe mySendMsg(String param) {
		return null;
	}

	private Result  getRedisMyData(String uuid) throws InterruptedException {
		Result result = new Result();
		String data = null;
		for (int i = 0; i < 5; i++) {
			Thread.sleep(300);
			data = cacheComponent.getRaw(uuid);
			if (!CommonUtil.isEmpty(data)){
				break;
			}
		}
		if (CommonUtil.isEmpty(data)){
			result.setData("数据为空");
			result.setCode(Result.Code.FAILED);
		}else {
			JSONObject jsonObj = JSONObject.parseObject(data);
			result.setData(jsonObj);
		}
		return result;
	}

}
